package com.chapter.sample.juc.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicStampedReference;

public class ABADemo {
    static AtomicInteger atomicInteger = new AtomicInteger(100);
    static AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference(100, 1);
    public static void main(String[] args) throws InterruptedException {

        new Thread(() -> {
            int stamp = atomicStampedReference.getStamp();
            System.out.println(Thread.currentThread().getName() + "---默认版本号：" + stamp);
            //让后面的T4和T3获得一样的版本号，都是“1”，好比较
            try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {throw new RuntimeException(e);}
            atomicStampedReference.compareAndSet(100, 101, stamp, stamp + 1);
            System.out.println(Thread.currentThread().getName() + "---1次版本号：" + atomicStampedReference.getStamp());
            atomicStampedReference.compareAndSet(101, 100, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1);
            System.out.println(Thread.currentThread().getName() + "---2次版本号：" + atomicStampedReference.getStamp());
        }, "t3").start();

        new Thread(() -> {
            int stamp = atomicStampedReference.getStamp();
            System.out.println(Thread.currentThread().getName() + "---默认版本号：" + stamp);
            //让上面的T3完成ABC问题
            try {TimeUnit.SECONDS.sleep(3);} catch (InterruptedException e) {throw new RuntimeException(e);}
            boolean flag = atomicStampedReference.compareAndSet(100, 200001, stamp, stamp + 1);
            System.out.println(Thread.currentThread().getName() + "操作释放成功 flag : " + flag+" - 版本号 ： "+ atomicStampedReference.getStamp()+" 值 ： "+atomicStampedReference.getReference());
//            System.out.println(Thread.currentThread().getName() + "---1次版本号：" + atomicStampedReference.getStamp());
//            atomicStampedReference.compareAndSet(101, 100, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1);
//            System.out.println(Thread.currentThread().getName() + "---2次版本号：" + atomicStampedReference.getStamp());
        }, "t4").start();
    }

    private static void abaProblem() throws InterruptedException {
        new Thread(() -> {
            atomicInteger.compareAndSet(100, 101);
            atomicInteger.compareAndSet(101, 100);
        });

        TimeUnit.SECONDS.sleep(2);
        new Thread(() -> {
            boolean flag = atomicInteger.compareAndSet(100, 2000);
            System.out.println(Thread.currentThread().getName() + "修改成功否：" + flag + "值" + atomicInteger.get());
        });
    }
}
